package com.emmmya.harinCheck.engine;

import com.emmmya.harinCheck.exception.HarinCheckException;
import com.emmmya.harinCheck.result.CheckResult;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Harin
 * @version 1.0
 * @date 2022-04-29 19:46:10
 */
public abstract class AbsHarinCheckEngine implements HarinCheckEngine{
    private static List<Class<?>> classeList ;
    //正数、负数、和小数：^(\-|\+)?\d+(\.\d+)?$
    public static String NUMBER_PATTERN  = "^(\\-|\\+)?\\d+(\\.\\d+)?$";

    static {
        Class<?>[] temp = new Class[]{String.class,Integer.class,Long.class,Float.class,Double.class,
                Character.class,Boolean.class,Byte.class,Short.class};
        classeList = Arrays.stream(temp).collect(Collectors.toList());
    }

    private String name ;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public abstract CheckResult depthCheck(Object obj) throws HarinCheckException;

    /**
     * 给该字段生成默认值
     * @param field
     * @param value
     * @return
     */
    public Object generateDefaultValue(Field field, String value) {
        try {
            Class<?> type = field.getType();
            if (classeList.contains(type)) {
                Constructor<?> constructor = type.getConstructor(String.class);
                Object o = constructor.newInstance(value);
                return o;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
